<template>
  <div class="signed-box">
    <div class="tabboxSigned">
      <a-list item-layout="horizontal" :data-source="categorieslistAll">
        <a-list-item slot="renderItem" slot-scope="item" class="category">
          <a-list-item-meta :description="item.description">
            <div slot="title" style="font-size: 16px">{{ item.name }}</div>
          </a-list-item-meta>
          <div>
            <a-icon type="form" style="font-size: 20px; color: #bdbcbf" @click="updateCategory" />
          </div>
        </a-list-item>
      </a-list>
      <a-form :form="signForm" :label-col="{ span: 24 }" :wrapper-col="{ span: 18 }" :colon="true">
        <a-form-item>
          <div class="labels">
            <p></p>
            签署方式
          </div>
          <a-select
            v-decorator="['signType', { rules: [{ required: false, message: '签署方式不能为空' }] }]"
            placeholder="请选择"
            style="width: 360px"
            @change="selectSignWays"
          >
            <a-select-option v-for="(form, index) in signedWay" :key="index" :value="form.value">{{ form.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-show="!personOnly">
          <div class="labels">
            <p></p>
            加盖印章
          </div>
          <div v-if="$route.meta.pageType">
            <a-select style="width: 360px" :disabled="true"> </a-select>
          </div>
          <div v-else>
            <div class="tips">选择该合同类型加盖的企业印章</div>
            <a-select
              v-decorator="['enterpriseSealId', { rules: [{ required: false, message: '印章不能为空' }] }]"
              placeholder="请选择"
              style="width: 360px"
              @change="watchChange"
            >
              <a-select-option v-for="(seal, index) in sealList" :key="index" :value="seal.id">{{ seal.name }}</a-select-option>
            </a-select>
            <span class="tips" style="margin-left: 16px; color: #666666" v-if="sealList.length > 0">
              {{ signForm.getFieldValue("enterpriseSealId") ? "已选择" : "未选择" }}
              <span style="margin-left: 4px; color: #252525">{{ sealFun(signForm.getFieldValue("enterpriseSealId"), "name") }}</span>
            </span>
            <span class="tips" style="margin-left: 16px" v-else>
              无开通成功的电子印章，
              <a-button type="link" @click="createSeal"> 去创建 </a-button>
            </span>
            <div class="sealimg" v-if="signForm.getFieldValue('enterpriseSealId')">
              <img :src="sealFun(signForm.getFieldValue('enterpriseSealId'), 'img')" alt="" srcset="" />
            </div>
          </div>
        </a-form-item>

        <a-form-item v-if="!enterpriseOnly">
          <div class="labels">
            <p></p>
            员工签署有效期
          </div>
          <div class="tips">发起签署后，员工签署方如未在设定有效期间签订，合同将自动撤回</div>
          <a-select
            v-decorator="['expireDays', { rules: [{ required: false, message: '员工签署有效期不能为空' }] }]"
            placeholder="请选择"
            style="width: 360px"
            @change="watchChange"
          >
            <a-select-option v-for="(time, index) in validityDay" :key="index" :value="time.id">{{ time.day }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <div class="labels">
            <p></p>
            合同类型
          </div>
          <!-- <a-input v-decorator="['fileType',{rules:[{required:false, message:'请选择'}]}]" :placeholder="currentCategory.fileType" style="width: 360px;margin: 24px;" @click="fileVisible=true" /> -->
          <a-select
            v-decorator="[
              'fileType',
              {
                rules: [{ required: true, message: '合同类型不能为空' }]
              }
            ]"
            placeholder="请选择"
            style="width: 360px"
            :allow-clear="false"
            @change="watchChange($event)"
          >
            <a-select-option v-for="(enumerate, index) in enumeratelist" :key="index" :value="enumerate.value">{{
              enumerate.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>

      <!-- 编辑合同类型信息 -->
      <a-modal title="编辑" :visible="updateVisible" :confirm-loading="confirmLoading" @ok="confirmAddType" @cancel="updateVisible = false">
        <div>
          <a-form :form="updateForm" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }" :colon="true">
            <a-form-item label="合同模板名称">
              <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入' }] }]" />
            </a-form-item>
            <a-form-item label="选择分组" v-if="$route.meta.pageType">
              <a-select v-decorator="['groupId', { initialValue: 0 }, { rules: [{ required: true, message: '请选择' }] }]">
                <a-select-option :value="0">系统提供合同模板</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="选择分组" v-else>
              <a-select v-decorator="['groupId', { rules: [{ required: true, message: '请选择' }] }]">
                <a-select-option v-for="(group, index) in groupList" :key="index" :value="group.id">{{ group.name }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="名称描述">
              <a-textarea
                v-decorator="['description', { rules: [{ required: false, message: '请输入' }] }]"
                :maxLength="255"
                placeholder="请输入名称描述"
                :rows="4"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
    <div class="btnlines" :class="isContainByString('contractAdmin') ? 'w-232' : ''">
      <a-button type="primary" style="margin-left: 12px" @click="saveSign">下一步</a-button>
    </div>
  </div>
</template>
<script>
import { parseQueryString, buildTabUrl, isContainByString } from "@/utils/index";
import { getCategoriesDetail, updateCategories, getContractGroups, getSealListAll, updateByAdmin } from "@/api/company/contract";
export default {
  data() {
    return {
      isContainByString,
      buildTabUrl,
      parseQueryString,
      updateVisible: false,
      confirmLoading: false,
      companyId: this.$store.state.hr.companyId,
      updateForm: this.$form.createForm(this, { name: "updateForm" }),
      signForm: this.$form.createForm(this, { name: "signForm" }),
      fileForm: this.$form.createForm(this, { name: "fileForm" }),
      groupList: [],
      currentCategory: {},
      categorieslistAll: [],
      sealList: [],
      personOnly: false,
      enterpriseOnly: false,
      fileTypeChange: false,
      signedWay: [
        {
          name: "企业-员工双方签署 (默认员工先行签署，企业再签署)",
          value: "both"
        },
        {
          name: "员工单方签署",
          value: "person_only"
        },
        {
          name: "企业单方签署",
          value: "enterprise_only"
        }
      ],
      validityDay: [
        { day: "长期有效", id: -1 },
        { day: "1天", id: 1 },
        { day: "2天", id: 2 },
        { day: "3天", id: 3 },
        { day: "4天", id: 4 },
        { day: "5天", id: 5 },
        { day: "6天", id: 6 },
        { day: "7天", id: 7 },
        { day: "8天", id: 8 },
        { day: "9天", id: 9 },
        { day: "10天", id: 10 },
        { day: "11天", id: 11 },
        { day: "12天", id: 12 },
        { day: "13天", id: 13 },
        { day: "14天", id: 14 },
        { day: "15天", id: 15 },
        { day: "16天", id: 16 },
        { day: "17天", id: 17 },
        { day: "18天", id: 18 },
        { day: "19天", id: 19 },
        { day: "20天", id: 20 },
        { day: "21天", id: 21 },
        { day: "22天", id: 22 },
        { day: "23天", id: 23 },
        { day: "24天", id: 24 },
        { day: "25天", id: 25 },
        { day: "26天", id: 26 },
        { day: "27天", id: 27 },
        { day: "28天", id: 28 },
        { day: "29天", id: 29 },
        { day: "30天", id: 30 }
      ],
      enumeratelist: [
        { name: "固定期限劳动合同", value: "laborContractLimit" },
        { name: "无固定期限劳动合同", value: "laborContractUnlimit" },
        {
          name: "以完成一定工作任务为期限的劳动合同",
          value: "laborContractJobs"
        },
        { name: "实习协议", value: "internAccords" },
        { name: "劳务合同", value: "laborContract" },
        { name: "返聘协议", value: "reemployAccords" },
        { name: "劳务派遣合同", value: "laborContractDispatch" },
        { name: "借调合同", value: "borrowedContract" },
        { name: "约定书", value: "engagementLetter" },
        { name: "兼职合同", value: "partTime" },
        { name: "见习协议", value: "noviciateAgreement" },
        { name: "离职合同", value: "dimissionContract" },
        { name: "退休返聘合同", value: "retireReEmploy" },
        { name: "其它", value: "other" }
      ]
    };
  },
  created() {
    this.getDetail();
    this.initValue();
    if (!this.$route.meta.pageType) {
      this.getSealList();
    }
  },
  methods: {
    initValue() {
      if (sessionStorage.getItem("signedsStatus")) {
        const categoryUpdateDTOFront = JSON.parse(sessionStorage.getItem("categoryUpdateDTO"));
        if (categoryUpdateDTOFront.signType === "person_only") {
          this.personOnly = true;
        } else {
          this.personOnly = false;
        }
        if (categoryUpdateDTOFront.signType === "enterprise_only") {
          this.enterpriseOnly = true;
        } else {
          this.enterpriseOnly = false;
        }
        setTimeout(() => {
          this.signForm.setFieldsValue({
            signType: categoryUpdateDTOFront.signType || this.signedWay[0].value,
            enterpriseSealId: categoryUpdateDTOFront.enterpriseSealId || undefined,
            expireDays: categoryUpdateDTOFront.expireDays || this.validityDay[0].id,
            fileType: categoryUpdateDTOFront.fileType || undefined
          });
        }, 0);
      }
    },
    getDetail(t) {
      this.categorieslistAll = [];
      const id = this.$route.query.id;
      getCategoriesDetail(id, this.$route.meta.pageType).then((res) => {
        this.categorieslistAll.push(res.data);
        this.currentCategory = res.data;
        if (t !== "edit") {
          if (!sessionStorage.getItem("signedsStatus")) {
            if (this.currentCategory.signType === "person_only") {
              this.personOnly = true;
            } else {
              this.personOnly = false;
            }
            if (this.currentCategory.signType === "enterprise_only") {
              this.enterpriseOnly = true;
            } else {
              this.enterpriseOnly = false;
            }
            setTimeout(() => {
              this.signForm.setFieldsValue({
                signType: this.currentCategory.signType || this.signedWay[0].value,
                enterpriseSealId: this.currentCategory.enterpriseSealId || undefined,
                expireDays: this.currentCategory.expireDays || this.validityDay[0].id,
                fileType: this.currentCategory.fileType || undefined
              });
            });
          }
        }
      });
    },
    // 获取分组列表
    getContractGroups() {
      getContractGroups({
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      }).then((res) => {
        this.groupList = res.data;
      });
    },
    // 获取印章列表
    getSealList() {
      const data = {
        status: 1,
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      };
      getSealListAll(data).then((res) => {
        this.sealList = res.data;
      });
    },
    updateCategory() {
      this.updateVisible = true;
      if (this.$route.meta.pageType) {
        setTimeout(() => {
          this.updateForm.setFieldsValue({
            name: this.currentCategory.name,
            description: this.currentCategory.description
          });
        });
      } else {
        this.getContractGroups();
        setTimeout(() => {
          this.updateForm.setFieldsValue({
            name: this.currentCategory.name,
            description: this.currentCategory.description,
            groupId: this.currentCategory.groupId
          });
        });
      }
    },
    // 确定编辑合同分类
    confirmAddType(e) {
      e.preventDefault();
      this.updateForm.validateFields((err, values) => {
        values.sort = "1";
        if (!err) {
          const types = this.isContainByString("console") || this.isContainByString("contractAdmin");
          if (this.$route.meta.pageType) {
            const v = {
              id: this.$route.query.id,
              name: values.name,
              groupId: values.groupId,
              description: values.description,
              subjectId: types ? "0" : this.$store.state.hr.companyId
            };
            updateByAdmin(v).then((res) => {
              this.$message.success("编辑成功");
              sessionStorage.setItem("contractTypeQueryName", values.name);
              this.updateVisible = false;
              this.updateForm.resetFields();
              this.getDetail("edit");
            });
          } else {
            const json = {
              ...values,
              subjectId: types ? "0" : this.$store.state.hr.companyId,
              id: this.$route.query.id
            };
            if (this.isContainByString("contractAdmin")) json.isSiteUpdate = true;
            updateCategories(json).then((res) => {
              this.$message.success("编辑成功");
              const path = this.$router.history.current.path;
              const query = this.$router.history.current.query;
              const newQuery = JSON.parse(JSON.stringify(query));
              newQuery.groupId = values.groupId;
              this.$router.replace({ path, query: newQuery });
              sessionStorage.setItem("contractTypeQueryName", values.name);
              this.updateVisible = false;
              this.updateForm.resetFields();
              this.getDetail("edit");
            });
          }
        }
      });
    },
    createSeal() {
      this.$router.push({
        path: "stamp"
      });
    },
    selectSignWays(e) {
      if (e === "person_only") {
        this.personOnly = true;
      } else {
        this.personOnly = false;
      }
      if (e === "enterprise_only") {
        this.enterpriseOnly = true;
      } else {
        this.enterpriseOnly = false;
      }
      setTimeout(() => {
        this.signForm.setFieldsValue({
          enterpriseSealId: undefined
        });
      });
    },
    watchChange(e) {
      this.sealList.some((ele, i) => {
        if (ele.id === e) {
          return true;
        }
      });
      const fileChangeItem = this.enumeratelist.filter((item) => item.value === e);
      if (fileChangeItem.length > 0) {
        this.fileTypeChange = true;
      } else {
        this.fileTypeChange = false;
      }
    },
    // 签署方式保存
    saveSign() {
      this.signForm.validateFields((err, values) => {
        values.sort = "1";
        if (!err) {
          if (values.signType === "person_only") {
            delete values.enterpriseSealId;
          }
          var categoryUpdateDTO = {
            ...values
          };

          sessionStorage.setItem("signedsStatus", "signedsStatus");
          sessionStorage.setItem("cateSignType", values.signType);
          sessionStorage.setItem("categoryUpdateDTO", JSON.stringify(categoryUpdateDTO));
          this.setNextCurrent();
        }
      });
    },
    setNextCurrent(val) {
      this.$emit("upData", 1);
    },
    sealFun(v, t) {
      const json = {};
      this.sealList.some((e) => {
        if (e.id === v) {
          json.name = e.name;
          json.img = e.sealString;
          return true;
        }
      });
      return json[t];
    }
  }
};
</script>
<style lang="scss" scoped>
.signed-box {
  // position: relative;
  // height: calc(100vh - 384px);
  padding-bottom: 70px;
  .tabboxSigned {
    padding: 0 24px;
    background: #fff;
    .ant-list-split .ant-list-item:last-child {
      border-bottom: 1px solid #e8e8e8;
    }
    .category {
      min-height: 80px;
      padding: 0 24px 12px 24px;
      margin-bottom: 24px;
    }
    .labels {
      height: 20px;
      line-height: 20px;
      font-size: 16px;
      font-weight: 400;
      color: #252525;
      position: relative;
      padding-left: 12px;
      margin-bottom: 16px;
      p {
        position: absolute;
        top: 0;
        left: 0;
        width: 3px;
        height: 20px;
        background: #6a66f6;
        border-radius: 2px;
      }
    }
    .ant-form-item-control-wrapper {
      margin: 0 !important;
    }
    .sealimg {
      width: 110px;
      height: 110px;
      border-radius: 4px;
      border: 1px solid #e8e8e8;
      overflow: hidden;
      margin-top: 12px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .tips {
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.25);
      line-height: 12px;
      margin-bottom: 14px;
    }
  }
  .btnlines {
    width: calc(100% - 250px);
    height: 64px;
    border-top: 1px solid #e8e8e8;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: fixed;
    right: 20px;
    bottom: 20px;
    background: #fff;
    padding-right: 28px;
  }
  .w-232 {
    width: calc(100% - 232px) !important;
  }
}
</style>
